package bs.app.android;

import java.io.UnsupportedEncodingException;

import android.content.SharedPreferences;

public class RecordStore {
	
//	/** Authorization to allow access to any MIDlet suites. */
//	public static int AUTHMODE_ANY = 1;
//	/** Authorization to allow access only to the current MIDlet suite. */
//	public static int AUTHMODE_PRIVATE = 0;
	
//	/** Adds the specified RecordListener. */
//	void addRecordListener(RecordListener listener)
    
//	/** Returns the last time the record store was modified, in the format used by System.currentTimeMillis(). */
//	long getLastModified()

//	/** Returns the recordId of the next record to be added to the record store. */
//	public int getNextRecordID(){}

//	/** Removes the specified RecordListener. */
//	void removeRecordListener(RecordListener listener)

//	/** Changes the access mode for this RecordStore. */
//	void setMode(int authmode, boolean writable)
    
//	/** Returns the amount of space, in bytes, that the record store occupies. */
//	public int getSize(){}

//	/** Returns the amount of additional room (in bytes) available for this record store to grow. */
//	public int getSizeAvailable(){}

//	/** Each time a record store is modified (by addRecord, setRecord, or deleteRecord methods) its version is incremented. */
//	public int getVersion(){}

	private final static String[] lst = {"vMe"};
	private static String FILENAME = null;
	private final String RECORD = "RCD";
	private int m_EndID = 0;
	
	public void destroy(){
	}

	private RecordStore(String RecordName){
		FILENAME = RecordName + "_vMe";
		
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);
		m_EndID = settings.getInt("NUM", 1);
		//System.out.println(">> m_EndID="+m_EndID+" Size="+settings.getAll().size());
		if(m_EndID < settings.getAll().size()){
			//System.out.println("ReBuild Record Sore!");
			deleteRecordStore(FILENAME);
			m_EndID = 1;
		}
	}
	
	/** Open (and possibly create) a record store associated with the given MIDlet suite. */
	public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary)  throws RecordStoreException {
		return new RecordStore(recordStoreName);
	}
	
	/** Open (and possibly create) a record store that can be shared with other MIDlet suites. */
	public static RecordStore openRecordStore(String recordStoreName, boolean createIfNecessary, int authmode, boolean writable)  throws RecordStoreException {
		return openRecordStore(recordStoreName, createIfNecessary);
	}
    
	/** Open a record store associated with the named MIDlet suite. */
	public static RecordStore openRecordStore(String recordStoreName, String vendorName, String suiteName)  throws RecordStoreException {
		return openRecordStore(recordStoreName, false);
	}

	/** This method is called when the MIDlet requests to have the record store closed. */
	public void closeRecordStore() {
		// nothing to do
	}
	
	/** The record is deleted from the record store. */
	public void deleteRecord(int recordId) {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);
		if(settings == null || !(recordId >= 0 && recordId <= m_EndID))
			return;
		
		SharedPreferences.Editor editor = settings.edit();
		editor.remove(RECORD + recordId);
		editor.commit();
	}
	
	/** Returns an array of the names of record stores owned by the MIDlet suite. */
	public static String[] listRecordStores() {
		return lst;
	}

	/** Deletes the named record store. */
	public static void deleteRecordStore(String m_rec_store) {
		SharedPreferences settings = Static.App.getSharedPreferences(m_rec_store, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.clear();
		editor.commit();
	}
	
	// READ ----------------------------------
	/** Returns an enumeration for traversing a set of records in the record store in an optionally specified order. */
	public RecordEnumeration enumerateRecords(RecordFilter filter, RecordComparator comparator, boolean keepUpdated){
		return new RecordEnumeration(this);
	}

	/** Returns the number of records currently in the record store. */
	public int getNumRecords() {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);
		int n = settings.getAll().size()-1; 
		return n < 0 ? 0 : n;
	}

	/** Returns the size (in bytes) of the MIDlet data available in the given record. */
	public int getRecordSize(int recordId) {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);

		if(settings == null || !(recordId >= 0 && recordId <= m_EndID))
			return -1;
		
		return settings.getString(RECORD + recordId, "").length();
	}

	/** Returns a copy of the data stored in the given record. */
	public byte[] getRecord(int recordId){
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);

		if(settings == null || !(recordId >= 1 && recordId <= m_EndID))
			return null;

		try {
			String str = settings.getString(RECORD + recordId, "");
			if(str.equals(""))
				return null;
			return str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/** Returns the data stored in the given record. 
	 * @throws Exception */
	public int getRecord(int recordId, byte[] arrByte, int iOffset) throws Exception {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);

		if(settings == null || !(recordId >= 1 && recordId <= m_EndID)){
			throw new Exception("Error: getRecord()");
		}

		try {
			String str = settings.getString(RECORD + recordId, "");
			if(str.equals(""))
				return 0;
			if(str.length() <= iOffset)
				return 0;
			byte arrSrc[] = str.getBytes("UTF-8");
			int len = str.length() - iOffset;
			System.arraycopy(arrSrc, iOffset, arrByte, 0, len);
			return len;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	/** Returns the name of this RecordStore. */
	public String getName(){
		return FILENAME;
	}
	
	/** Returns the Record ID end of this RecordStore. */
	public int getRecordIdEnd(){
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);
		return settings.getInt("NUM", 1);
	}
	// WRITE ----------------------------------
	/** Adds a new record to the record store. */
	public void addRecord(byte[] arrByte, int iOffset, int count) {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);

		if(arrByte==null || iOffset + count > arrByte.length)
			return;
		
		try {
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(RECORD + m_EndID , new String(arrByte,iOffset, count,"UTF-8"));
			m_EndID++;
			editor.putInt("NUM" , m_EndID);
			editor.commit();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}

	/** Sets the data in the given record to that passed in. */
	public void setRecord(int recordId, byte[] arrByte, int iOffset, int count) {
		SharedPreferences settings = Static.App.getSharedPreferences(FILENAME, 0);
		
		if(arrByte==null || iOffset + count > arrByte.length)
			return;
		
		if(settings == null || !(recordId >= 1 && recordId <= m_EndID))
			return;

		try {
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(RECORD + recordId , new String(arrByte,iOffset, count,"UTF-8"));
			editor.commit();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
